<?php
// your registration data
$mrh_pass2 = "pass2";   // merchant pass2 here

// HTTP parameters:
$out_summ = $_REQUEST["OutSum"];
$inv_id = $_REQUEST["InvId"];
$crc = $_REQUEST["SignatureValue"];
$shp_item = $_REQUEST["Shp_item"];
$shp_mode = $_REQUEST["Shp_mode"];

//print_r ($_REQUEST);
//echo "<br>";
//echo "<br>";
// HTTP parameters: $out_summ, $inv_id, $crc
$crc = strtoupper($crc);   // force uppercase

// build own CRC
$my_crc = strtoupper(md5("$out_summ:$inv_id:$mrh_pass2:Shp_item=$shp_item:Shp_mode=$shp_mode"));

if (strtoupper($my_crc) != strtoupper($crc))
{
  echo "bad sign\n";
  exit();
}

// print OK signature
//echo "OK$inv_id\n";

// perform some action (change order state to paid)
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
//define ('LMI_MODE', '1');
//$messages = Array();

//function debug_msg( $msg ) {
//    global $messages;
//    if( $shp_mode == "0" ) {
//        if( !defined( "_DEBUG_HEADER")  ) {
//            echo "<h2>RoboKassa Notify_rk.php Debug OUTPUT</h2>";
//            define( "_DEBUG_HEADER", "1" );
//        }
//        $messages[] = "<pre>$msg</pre>";
//        echo end( $messages );
//    }
//}
//print_r ($_POST);
if ($_POST) {
	header("HTTP/1.0 200 OK");

    global $mosConfig_absolute_path, $mosConfig_live_site, $mosConfig_lang, $database,
    $mosConfig_mailfrom, $mosConfig_fromname;
    
        /*** access Joomla's configuration file ***/
        $my_path = dirname(__FILE__);
        
        if( file_exists($my_path."/../../../configuration.php")) {
            $absolute_path = dirname( $my_path."/../../../configuration.php" );
            require_once($my_path."/../../../configuration.php");
        }
        elseif( file_exists($my_path."/../../configuration.php")){
            $absolute_path = dirname( $my_path."/../../configuration.php" );
            require_once($my_path."/../../configuration.php");
        }
        elseif( file_exists($my_path."/configuration.php")){
            $absolute_path = dirname( $my_path."/configuration.php" );
            require_once( $my_path."/configuration.php" );
        }
        else {
            die( "Joomla Configuration File not found!" );
        }
        
        $absolute_path = realpath( $absolute_path );
        
        // Set up the appropriate CMS framework
        if( class_exists( 'jconfig' ) ) {
			define( '_JEXEC', 1 );
			define( 'JPATH_BASE', $absolute_path );
			define( 'DS', DIRECTORY_SEPARATOR );
			// Load the framework
			require_once ( JPATH_BASE . DS . 'includes' . DS . 'defines.php' );
			require_once ( JPATH_BASE . DS . 'includes' . DS . 'framework.php' );
			// create the mainframe object
			$mainframe = & JFactory::getApplication( 'site' );
			
			// Initialize the framework
			$mainframe->initialise();
			
			// load system plugin group
			JPluginHelper::importPlugin( 'system' );
			
			// trigger the onBeforeStart events
			$mainframe->triggerEvent( 'onBeforeStart' );
			$lang =& JFactory::getLanguage();
			$mosConfig_lang = $GLOBALS['mosConfig_lang']          = strtolower( $lang->getBackwardLang() );
			// Adjust the live site path
			$mosConfig_live_site = str_replace('/administrator/components/com_virtuemart', '', JURI::base());
			$mosConfig_absolute_path = JPATH_BASE;
//			debug_msg( "0. Finished Initialization of the joomla1.5 config" );
} else {
        	define('_VALID_MOS', '1');
        	require_once($mosConfig_absolute_path. '/includes/joomla.php');
        	require_once($mosConfig_absolute_path. '/includes/database.php');
        	$database = new database( $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix );
        	$mainframe = new mosMainFrame($database, 'com_virtuemart', $mosConfig_absolute_path );
        }

        // load Joomla Language File
        if (file_exists( $mosConfig_absolute_path. '/language/'.$mosConfig_lang.'.php' )) {
            require_once( $mosConfig_absolute_path. '/language/'.$mosConfig_lang.'.php' );
        }
        elseif (file_exists( $mosConfig_absolute_path. '/language/english.php' )) {
            require_once( $mosConfig_absolute_path. '/language/english.php' );
        }
    /*** END of Joomla config ***/
    
    
    /*** VirtueMart part ***/
		global $database;        
        require_once($mosConfig_absolute_path.'/administrator/components/com_virtuemart/virtuemart.cfg.php');
        include_once( ADMINPATH.'/compat.joomla1.5.php' );
        require_once( ADMINPATH. 'global.php' );
        require_once( CLASSPATH. 'ps_main.php' );
		require_once( CLASSPATH. 'ps_database.php' );
		require_once( CLASSPATH. 'ps_order.php' );

        /* @MWM1: Logging enhancements (file logging & composite logger). */
        $vmLogIdentifier = "notify_rk.php";
        require_once(CLASSPATH."Log/LogInit.php");
              
        /* Load the PayPal Configuration File */ 
        require_once( CLASSPATH. 'payment/ps_robokassa.cfg.php' );
        
		if( LMI_MODE == "1" ) {
			$debug_email_address = $mosConfig_mailfrom;
		}
		else {
			$debug_email_address = $mosConfig_mailfrom;
		}
	    $sess = new ps_session();                        
    /*** END VirtueMart part ***/

/*==================================== WENBONEY PART ============================================*/

/*=======================    Формы предварительного запроса   	================================ */

	$post_msg = "";
	$pure_feedback 	= array();
	
	foreach ($_POST as $ipnkey => $ipnval) {
        $post_msg .= "$ipnkey=$ipnval&amp;";
}
	
	$post_msg = "";
	
	/*if( LMI_MODE == "1" ){
   	 debug_msg( "2. Received POST" );
	}*/
    
	foreach ($_POST as $ipnkey => $ipnval) {
		// Fix issue with magic quotes
		if (get_magic_quotes_gpc())	{
			$ipnkey = stripslashes ($ipnkey);
			$ipnval = stripslashes ($ipnval);
		}
		// ^ Antidote to potential variable injection and poisoning    
        if (!eregi("^[_0-9a-z-]{1,30}$",$ipnkey))  { 
            unset ($ipnkey); 
            unset ($ipnval); 
        } 
		$pure_feedback[$ipnkey] = $ipnval;
    } 
	//transaction
$rk_post_7	= $_POST[inv_id];		//	Номер счета в системе WebMoney Transfer, выставленный покупателю от имени продавца в процессе обработки запроса на выполнение платежа сервисом WebMerchantInterface. 
$rk_post_10 = $_POST[crc];				//	Контрольная подпись оповещения о выполнении платежа, которая используется для проверки целостности полученной информации и однозначной идентификации отправителя.

	foreach ($pure_feedback as $rk_name => $rk_value){
		if($rk_name == InvId){
			$invoice = $rk_value;
		}
		if($rk_name == OutSum){
			$final_cost = $rk_value;
		}
		if($rk_name == LMI_PREREQUEST){
			$prerequest_mode = $rk_value;
		}
	}
	
print_r ($pure_feedback);
	
if ($prerequest_mode == "1")
{	
	
    $qv = "SELECT `order_id`, `order_number`, `user_id`, `order_subtotal`,
                    `order_total`, `order_currency`, `order_tax`, 
                    `order_shipping_tax`, `coupon_discount`, `order_discount`, `ip_address`
                FROM `#__{vm}_orders` 
                WHERE `order_id`='".$invoice."'";
	$db_rk = new ps_DB;
	$query = $db_rk->query($qv);		
    $db_rk->query($qv);
    $db_rk->next_record();
	if( $db_rk->f( 'order_id' ) ) {
		$order_id = $db_rk->f( 'order_id' );
		if(!$order_id or $order_id=="") {
			$err=1;
			echo "ERR: НЕТ ТАКОГО ТОВАРА";
			exit;
		}
	}
	  
	if( $db_rk->f( 'order_total' ) ) {
		$order_total_cost = $db_rk->f( 'order_total' );
		if(!$order_total_cost or $order_total_cost=="") {
			$err=1;
			echo "ERR: НЕТ ТАКОЙ ЦЕНЫ";
			exit;
		}
		if ($order_total_cost != $final_cost){
			$err=1;
			$shop_user = $db_rk->f( 'user_id' );
			$user_ip = $db_rk->f( 'ip_address' );
			echo "ERR: НЕВЕРНАЯ СУММА ".$final_cost;
				
				//notify shop owner about possible fraud
           		$mailsubject = "Попытка взлома магазина ";
				$mailbody = "ЗАФИКСИРОВАНА ПОПЫТКА ИЗМЕНЕНИЯ СТОИМОСТИ ОПЛАТЫ \n\n";
            	$mailbody .= "Заказ номер : ".$order_id." \n";
				$mailbody .= "Номер покупателя в магазине : ".$shop_user." \n";
				$mailbody .= "IP address : ".$user_ip." \n";
				$mailbody .= "Настоящая цена : ".$order_total_cost." \n";
				$mailbody .= "Измененная цена : ".$final_cost." \n";
				vmMail( $mosConfig_mailfrom, $mosConfig_fromname, $debug_email_address, $mailsubject, $mailbody ); 
	
			exit;
		}
	  }
	if(!$err){
		echo "YES";
	}
}
/*==============================================  Форма оповещения о платеже  ===========================================*/
else 
{
		$qv = "SELECT `order_id`, `order_number`, `user_id`, `order_subtotal`,
						`order_total`, `order_currency`, `order_tax`, 
						`order_shipping_tax`, `coupon_discount`, `order_discount`, `ip_address`
					FROM `#__{vm}_orders` 
					WHERE `order_id`='".$invoice."'";
		$db_rk = new ps_DB;
		$query = $db_rk->query($qv);		
		$db_rk->query($qv);
		$db_rk->next_record();
		$order_total_cost = $db_rk->f( 'order_total' );
		$shop_user = $db_rk->f( 'user_id' );
		$user_ip = $db_rk->f( 'ip_address' );
		$order_id = $db_rk->f( 'order_id' );

//------------------------------------------------------------------------------------------------------------------- 

$mrh_pass2 = "pass2";
$out_summ = $_REQUEST["OutSum"];
$inv_id = $_REQUEST["InvId"];
$crc = $_REQUEST["SignatureValue"];
$shp_item = $_REQUEST["Shp_item"];
$shp_mode = $_REQUEST["Shp_mode"];

$my_crc = strtoupper(md5("$out_summ:$inv_id:$mrh_pass2:Shp_item=$shp_item:Shp_mode=$shp_mode"));
//--------------------------------------------------------------------------------------------------------------------		 
		$hash = $my_crc;
		if($hash!=strtoupper($rk_post_10)) {
			$mailsubject = "Попытка взлома магазина ";
			$mailbody  = "Зафиксирована попытка изменения параметров оплаты\n\n";
			$mailbody .= "Подменили зашифрованный ключ HASH MD5\n";
			$mailbody .= "Заказ номер : ".$order_id." \n";
			$mailbody .= "Номер покупателя в магазине : ".$shop_user." \n";
			$mailbody .= "IP address : ".$user_ip." \n";
			$mailbody .= "Настоящая цена : ".$order_total_cost." \n";
			$mailbody .= "Измененная цена : ".$final_cost." \n";
			$mailbody .= "Полученный HASH : ".$rk_post_10." \n";
			$mailbody .= "Настоящий HASH  : ".$hash." \n";
			vmMail( $mosConfig_mailfrom, $mosConfig_fromname, $debug_email_address, $mailsubject, $mailbody ); 
			exit;
		}
		else {
			$d['order_id'] = $order_id;
			$d['notify_customer'] = "Y";
			$d['order_total'] = $order_total_cost;
			$d['order_status'] = ROBOKASSA_VERIFIED_STATUS;                    
			$ps_order= new ps_order;
			$ps_order->order_status_update($d);
			
			$d['order_status'] = "Подтвержденный";
				
			$dbbt1 = new ps_DB;
			$q  = "SELECT * FROM #__{vm}_order_user_info WHERE order_id='" . $order_id . "' ORDER BY address_type ASC"; 
			$dbbt1->query($q);
			$dbbt1->next_record(); 
			$recipient = $dbbt1->f("user_email");
				
			$mailsubject = "Ваш заказ № ".$d['order_id']." оплачен.";
				
			$mailbody = "Ваш заказ № ".$d['order_id']." оплачен. \n\n";
			$mailbody .= "--------------------------------------- \n";
			$mailbody .= "Информация о заказе \n";
			$mailbody .= "Заказ №: ".$d['order_id']." \n";
			$mailbody .= "Статус заказа: ".$d['order_status']." \n";
			$mailbody .= "Цена: ".$d['order_total']." RUB \n";
			$mailbody .= "--------------------------------------- \n";
			$mailbody .= "Информация о заказчике \n\n";
			$mailbody .= "Компания: ".$dbbt1->f("company")." \n";
			$mailbody .= "Фамилия: ".$dbbt1->f("last_name")." \n";
			$mailbody .= "Имя: ".$dbbt1->f("first_name")." \n";
			$mailbody .= "Отчество: ".$dbbt1->f("middle_name")." \n";
			$mailbody .= "Страна: ".$dbbt1->f("country")." \n";
			$mailbody .= "Город: ".$dbbt1->f("city")." \n";
			$mailbody .= "Адрес: ".$dbbt1->f("address_1")." \n";
			$mailbody .= "Телефон: ".$dbbt1->f("phone_1")." \n";
			$mailbody .= "E-Mail: ".$dbbt1->f("user_email")." \n";
			$mailbody .= "--------------------------------------- \n";
			$mailbody .= "Информация об оплате \n\n";
			$mailbody .= "Сумма платежа: ".$d['order_total']." RUB. \n";
			$mailbody .= "Номер счета: ".$rk_post_7." \n";
				
			vmMail( $mosConfig_mailfrom, $mosConfig_fromname, $recipient, $mailsubject, $mailbody );
			vmMail( $mosConfig_mailfrom, $mosConfig_fromname, $debug_email_address, $mailsubject, $mailbody ); 
		}
		
}
}
echo "OK$_POST[inv_id]\n";
?>
